package game_frame

import (
	"context"
	"errors"
	"fmt"
	"gamesdk/clock"
	"gamesdk/common/log"
	"gamesdk/common/rand"
	"gamesdk/define"
	"gamesdk/global"
	"gamesdk/inter"
	"gamesdk/msg"
	"sync"
	"time"
	"unicode/utf8"

	"github.com/golang/protobuf/proto"
)

const (
	g_TableFree  = 0 //空闲
	g_TableStart = 1 //开始
	g_TableExit  = 2 //退出
)

type MsgTableChan struct {
	SubCmd int32
	Buffer []byte
	User   *User
}

type MsgMatchChan struct {
	msgId                int
	user                 *User
	roomId               int64
	roomProb             int32
	level                int32
	roomRate             int64
	entranceRestrictions int64
	adviceConfig         string
	chairId              int
	result               chan *MatchResult
	isOpenAiRobot        bool
}
type MatchResult struct {
	ok      int
	tableId int
	chairId int
}

type Table struct {
	id                   int                //桌子id
	max                  int                //最大椅子数量
	min                  int                //最小椅子数量
	count                int                //桌子总人数
	robotCount           int                //机器人数量
	status               int                //状态
	gameNum              string             //局id
	platformId           int64              //登录平台ID	记录登录的平台ID号
	entranceRestrictions int64              //入场条件
	roomID               int64              //房间id
	roomRate             int64              //房间税收
	adviceConfig         string             //自定义配置
	level                int32              //等级
	roomProb             int32              //雪池
	clock                *clock.Clock       //定时器
	msgBuff              chan *MsgTableChan //消息缓存
	userReady            chan *User         //用户准备
	userExit             chan *User         //用户退出
	userLeave            chan *User         //用户离开
	msgMatchChan         chan *MsgMatchChan //匹配消息
	timeCallBack         chan func()        //定时回调
	close                chan bool          //退出
	reset                chan bool          //重置
	chairs               []*Chair           //椅子管理器
	records              []*msg.GameLog     //操作日志
	interGame            inter.GameInter    //游戏逻辑逻辑
	room                 *Room              //房间逻辑
	waitInit             bool               //等待初始化
	isReset              bool               //重置中
	isOpenAiRobot        bool               //是否开启机器人
	endTable             int64              //结束时间
	lock                 sync.RWMutex
	ctx                  context.Context
}

func NewTable(id, max, min int, room *Room) *Table {
	defer log.Trace()()
	table := &Table{
		id:                   id,
		max:                  max,
		min:                  min,
		status:               g_TableFree,
		room:                 room,
		clock:                clock.CreateClock(),
		count:                0,
		robotCount:           0,
		adviceConfig:         "",
		platformId:           -1,
		entranceRestrictions: -1,
		roomID:               -1,
		level:                0,
		roomProb:             0,
		roomRate:             0,
		isOpenAiRobot:        true,
		waitInit:             true,
		isReset:              false,
		endTable:             0,
		msgMatchChan:         make(chan *MsgMatchChan, max),
		ctx:                  context.Background(),
	}
	table.funcInitChairs()
	return table
}

func (this *Table) GetGameNum() string {
	defer log.Trace()()
	return this.gameNum
}

func (this *Table) GetRoomRate() int64 {
	defer log.Trace()()
	return this.roomRate
}

func (this *Table) GetLevel() int32 {
	defer log.Trace()()
	return this.level
}

//初始化椅子
func (this *Table) funcInitChairs() {
	defer log.Trace()()
	this.chairs = make([]*Chair, this.max)
	for index := 0; index < len(this.chairs); index++ {
		this.chairs[index] = NewChair(index)
	}
}

//启动读
func (this *Table) funcRun(waitGroup *sync.WaitGroup) {
	defer log.Warn("退出主逻辑！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！")
	this.records = make([]*msg.GameLog, 0)
	this.msgBuff = make(chan *MsgTableChan, this.max)
	this.timeCallBack = make(chan func(), this.max)
	this.userReady = make(chan *User, this.max)
	this.userExit = make(chan *User, this.max)
	//this.sendScene = make(chan *User, this.max)
	this.userLeave = make(chan *User, this.max)

	this.close = make(chan bool)
	this.reset = make(chan bool)

	this.waitInit = false
	this.isReset = false
	//通知逻辑存储桌子
	this.room.interRoom.InitTableFrameSink(this)
	log.Test("房间逻辑启动 id:%d %d", this.id, this.count)
	//开启机器人
	this.RobotCheck()
	for {
		select {
		case msgMatchChan := <-this.msgMatchChan:
			if msgMatchChan == nil {
				log.Warn("match:%v", msgMatchChan)
			} else {
				log.Info("开始逻辑匹配%d", msgMatchChan.user.GetId())
				this.MatchMsg(msgMatchChan)
			}

		case fn := <-this.timeCallBack:
			if fn == nil {
				log.Warn("定时回调是nil")
			} else {
				this.TimerMsg(fn)
			}

		case user := <-this.userExit:
			if user == nil {
				log.Warn("user:%v", user)
			} else {
				u := this.room.userManager.GetById(user.GetId())
				if u != nil {
					this.UserExitMsg(u)
				}

			}

		case user := <-this.userLeave:
			if user == nil {
				log.Warn("user:%v", user)
			} else {
				u := this.room.userManager.GetById(user.GetId())
				if u != nil {
					this.UserLeaveMsg(u)
				}

			}
		// case user := <-this.sendScene:
		// 	if user == nil {
		// 		log.Warn("user:%v", user)
		// 	} else {
		// 		u := this.room.userManager.GetById(user.GetId())
		// 		if u != nil {
		// 			this.SendSenceMsg(u)
		// 		}
		// 	}
		case user := <-this.userReady:
			if user == nil {
				log.Warn("user:%v", user)
			} else {
				u := this.room.userManager.GetById(user.GetId())
				if u != nil {
					this.UserReadyMsg(u)
				}
			}

		case msg := <-this.msgBuff:
			if msg == nil {
				log.Warn("msg:%v", msg)
			} else {
				this.LogicMsg(msg)
				msg = nil
			}

		case <-this.reset:
			log.Test("开始重置房间:%d", this.id)
			this.isReset = true
			if this.count <= 0 {
				this.clock.Reset()
				//log.Test("开始重置房间")
				if this.roomID != -1 {
					if this.isReset == true {
						this.status = g_TableFree
						//this.EndGame()
						if global.G_Config.GameType == 1 || global.G_Config.GameType == 3 {
							this.room.openRoom.Delete(fmt.Sprintf("%d-%d", this.platformId, this.roomID))
						}
						this.count = 0
						this.adviceConfig = ""
						this.platformId = -1
						this.entranceRestrictions = -1
						this.roomID = -1
						this.level = 0
						this.roomProb = 0
						this.roomRate = 0
						this.status = g_TableFree

						for index := 0; index < len(this.chairs); index++ {
							this.chairs[index].Leave()
						}
						//通知逻辑重置
						log.Listen(this.interGame.ResetTable, func(f interface{}) {
							f.(func())()
						}, fmt.Sprintf("函数名称:this.interGame.ResetTable"))
						this.isReset = false
						log.Test("重置房间完成:%d", this.id)
					}
				} else {
					this.isReset = false
					log.Test("重置房间完成:%d", this.id)
				}
				this.RobotCheck()
			} else {
				this.interGame.CloseTable()
				log.Test("人数大于0，通知逻辑关闭房间，并等待重制")
			}
		case <-this.close:
			this.clock.Reset()
			waitGroup.Done()
			close(this.msgBuff)
			close(this.userReady)
			close(this.userExit)
			//close(this.sendScene)
			close(this.userLeave)
			close(this.timeCallBack)
			close(this.close)
			close(this.reset)
			panic("close!!!!")
		}
	}
}

func (this *Table) WriteLogs(userId int64, content string) {
	this.records = append(this.records, &msg.GameLog{
		UserId:  userId,
		Content: content,
	})
}

//开启定时检测机器人
func (this *Table) RobotCheck() {
	if global.G_Config.GameType == 1 || global.G_Config.GameType == 3 || global.G_Config.GameType == 5 {
		log.Info("开启机器人检测")
		this.AddTimerRepeat(time.Duration(30000), 0, this.funcRobotCheck)
	} else {
		log.Test("不是百人房间，不需要检测机器人")
	}
}

func (this *Table) funcRobotCheck() {
	_, ok := this.room.robotCtl.Load(fmt.Sprintf("%d-%d", this.platformId, this.roomID))
	if ok {
		//存在直接返回
		log.Test("此房间禁止机器人加入%d-%d", this.platformId, this.roomID)
		return
	}
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return
	}
	if this.roomID < 0 {
		//直接结束不检测
		log.Test("房间号不存在，直接不定时检测")
		return
	}
	if this.isReset == true {
		log.Test("重置房间不检查机器人")
		return
	}
	log.Info("此房间%d-%d机器人总数%d", this.platformId, this.roomID, this.robotCount)
	//表示可用直接分配
	//获取当前时间
	hour := time.Now().Hour()
	//判断存不存在机器人配置
	if len(global.G_Config.Robot) > 0 {
		minRobot := global.G_Config.Robot[hour][0]
		maxRobot := global.G_Config.Robot[hour][1]
		if this.robotCount < minRobot {
			//添加机器人
			count := rand.RandInt(minRobot, maxRobot)
			//log.Info("获取机器人%d-%d", this.platformId, this.roomID)
			log.Listen(this.room.funcGetRobot, func(f interface{}) {
				f.(func(platformId, roomId, tableId int64, num int32) error)(this.platformId, this.roomID, int64(this.id), int32(count-this.robotCount))
				log.Test("添加机器人")
			}, "")
			return
		}
		if this.robotCount > maxRobot {
			kickout := 0
			count := this.count - rand.RandInt(minRobot, maxRobot)
			//删除机器人
			for index := 0; index < len(this.chairs); index++ {
				//表示结算
				user := this.chairs[index].GetUser()
				if user != nil {
					if user.onlineStatus != g_UserLeave {
						if user.IsRobot() {
							if kickout >= count {
								break
							}
							//踢出多的机器人
							this.UserExitMsg(user)
							kickout++
						}
					}
				}
			}
			return
		}
		if this.robotCount >= minRobot && this.robotCount <= maxRobot {
			//中间人数
			number := rand.RandInt(minRobot, maxRobot)
			if number > this.robotCount {
				//添加机器人
				//log.Info("获取机器人%d-%d", this.platformId, this.roomID)
				log.Listen(this.room.funcGetRobot, func(f interface{}) {
					f.(func(platformId, roomId, tableId int64, num int32) error)(this.platformId, this.roomID, int64(this.id), int32(number-this.robotCount))
					log.Test("添加机器人")
				}, "")
				return
			}
			if number < this.robotCount {
				kickout := 0
				//删除机器人
				for index := 0; index < len(this.chairs); index++ {
					//表示结算
					user := this.chairs[index].GetUser()
					if user != nil {
						if user.onlineStatus != g_UserLeave {
							if user.IsRobot() {
								if kickout >= (this.robotCount - number) {
									break
								}
								//踢出多的机器人
								this.UserLeaveMsg(user)
								kickout++
							}
						}
					}
				}
				return
			}
		}
	}
}

//开始匹配
func (this *Table) SendMatchMsg(msgMatchChan *MsgMatchChan) {
	log.Listen(func(msgMatchChan *MsgMatchChan) {
		this.msgMatchChan <- msgMatchChan
	}, func(f interface{}) {
		f.(func(msgMatchChan *MsgMatchChan))(msgMatchChan)
	}, fmt.Sprintf("匹配消息 %d", msgMatchChan.user.GetId()))
}

//匹配消息
func (this *Table) MatchMsg(msgMatchChan *MsgMatchChan) {
	defer log.Trace()()
	log.Test("开始匹配:%d chairid:%d", msgMatchChan.user.GetId(), msgMatchChan.chairId)
	if msgMatchChan == nil {
		log.Warn("匹配消息为空")
		return
	}
	ok := define.SIT_DOWN_ERROR_NORMAL
	tableId := -1
	chairId := -1
	if time.Now().UnixNano()-this.endTable <= 1000000*50 {
		log.Warn("此房间正处于重置期间%d-%d:%d-%d", this.roomID, this.platformId, msgMatchChan.roomId, msgMatchChan.user.platformId)
		goto A
	}
	if this.roomID != -1 && this.platformId != -1 {
		if this.roomID != msgMatchChan.roomId || this.platformId != msgMatchChan.user.platformId {
			log.Warn("房间id或业主id不正确%d-%d:%d-%d", this.roomID, this.platformId, msgMatchChan.roomId, msgMatchChan.user.platformId)
			goto A
		}
	}
	if msgMatchChan.chairId >= 0 {
		ok = this.interGame.OnActionUserSitDown(msgMatchChan.user, msgMatchChan.chairId, msgMatchChan.adviceConfig)
		if ok == define.SIT_DOWN_OK {
			tableId = this.id
			chairId = msgMatchChan.chairId
			this.chairs[msgMatchChan.chairId].SetDown(msgMatchChan.user)
			msgMatchChan.user.SetTableId(this.id)
			msgMatchChan.user.SetChairId(msgMatchChan.chairId)
		} else {
			log.Test("逻辑不让用户坐下 %d ", msgMatchChan.user.GetId())
		}
	} else {
		if this.isReset == true {
			log.Warn("房间重制中，不能匹配")
			goto A
		}
		if this.adviceConfig != "" && this.adviceConfig != msgMatchChan.adviceConfig {
			log.Test("%d配置不相等，旧:%s-----新:%s", this.roomID, this.adviceConfig, msgMatchChan.adviceConfig)
			goto A
		}
		if this.platformId != -1 && this.platformId != msgMatchChan.user.platformId {
			log.Test("%d platformId不相等，旧:%d-----新:%d", this.roomID, this.platformId, msgMatchChan.user.platformId)
			goto A
		}
		if this.entranceRestrictions != -1 && this.entranceRestrictions != msgMatchChan.entranceRestrictions {
			log.Test("%d entranceRestrictions不相等，旧:%d-----新:%d", this.roomID, this.entranceRestrictions, msgMatchChan.entranceRestrictions)
			goto A
		}
		if this.roomID != -1 && this.roomID != int64(msgMatchChan.roomId) {
			log.Test("%d roomID不相等，旧:%d-----新:%d", this.roomID, this.roomID, msgMatchChan.roomId)
			goto A
		}
		// if this.level != 0 && this.level != msgMatchChan.level {
		// 	log.Test("%d level不相等，旧:%d-----新:%d", this.roomID, this.level, msgMatchChan.level)
		// 	goto A
		// }
		// if this.roomRate != 0 && this.roomRate != int64(msgMatchChan.roomRate) {
		// 	log.Test("%d roomRate不相等，新:%d-----旧:%d", this.roomID, this.roomRate, msgMatchChan.roomRate)
		// 	goto A
		// }
		ok, tableId, chairId = this.PlanChair(msgMatchChan.user, msgMatchChan.roomId, msgMatchChan.roomProb, msgMatchChan.level, msgMatchChan.roomRate, msgMatchChan.entranceRestrictions, msgMatchChan.adviceConfig)
	}
A:
	if ok == define.SIT_DOWN_OK {
		//匹配成功意味着启动了房间
		if global.G_Config.GameType == 1 || global.G_Config.GameType == 3 {
			this.room.openRoom.Store(fmt.Sprintf("%d-%d", this.platformId, this.roomID), int32(this.id))
		}

		if chairId < 0 || chairId > this.max {
			log.Error("椅子号不合法！！！！%d", chairId)
			//panic(fmt.Sprintf("椅子号不合法！！！！%d", chairId))
			ok = define.SIT_DOWN_ERROR_NORMAL
			goto A
		}

		c2sMatch := &msg.C2SCmdMatch{
			UserId:   msgMatchChan.user.id,
			ChairNum: int32(chairId),
			TableNum: int32(tableId),
			Result:   int32(ok),
		}
		buffer, _ := proto.Marshal(c2sMatch)

		msgMatchChan.user.funcSendMsg(int32(msg.CMDKIND_MATCH), c2sMatch.UserId, buffer)

		//广播用户匹配成功
		s2cEnter := &msg.S2CEnter{
			UserId:   msgMatchChan.user.id,      //用户ID
			Head:     msgMatchChan.user.head,    //头像url
			Gold:     msgMatchChan.user.balance, //用户金币
			NickName: msgMatchChan.user.nike,    //用户昵称
			Sign:     msgMatchChan.user.sign,    //用户签名
			TableId:  int32(tableId),            //桌子号
			SetId:    int32(chairId),            //椅子号
		}
		data, err := proto.Marshal(s2cEnter)
		if err != nil {
			log.Error(err.Error())
			ok = define.SIT_DOWN_ERROR_NORMAL
		} else {
			this.room.userManager.DeleteOfflineById(msgMatchChan.user.GetId())
			//添加用户
			this.room.userManager.Add(msgMatchChan.user)
			if msgMatchChan.user.isRobot {
				this.room.aiManager.AddRobot(msgMatchChan.user.GetId(), msgMatchChan.user)
			}
			this.chairs[chairId].SetDown(msgMatchChan.user)

			msgMatchChan.user.sendMsgF(int32(msg.MSGKIND_MATCH), data)

			log.UserInfoLog(msgMatchChan.user.GetId(), "广播用户匹配成功 TableNum:%d,ChairNum:%d, roomId:%d", tableId, chairId, msgMatchChan.roomId)
			this.SendScene(msgMatchChan.user)
			//log.Info("%d用户进入房间%d 椅子id:%d", msgMatchChan.user.id, this.id, msgMatchChan.user.GetChairId())
		}

	}
	matchResult := &MatchResult{ok: ok, tableId: tableId, chairId: chairId}
	//this.isOpenAiRobot = msgMatchChan.isOpenAiRobot
	if matchResult.ok == define.SIT_DOWN_OK {
		if msgMatchChan.isOpenAiRobot {
			this.funcRobotControl(msg.S2CRobotConfig_ON)
		} else {
			this.funcRobotControl(msg.S2CRobotConfig_OFF)
		}
	}

	//并且将结果返回给getway
	log.Info("开始返回匹配结果%d", msgMatchChan.user.GetId())
	msgMatchChan.result <- matchResult
	log.Info("返回匹配结果%d", msgMatchChan.user.GetId())
}

//定时器消息
func (this *Table) TimerMsg(fn func()) {
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return
	}
	if this.waitInit {
		log.Warn("该桌子已重置,等待用户匹配进入")
		return
	}
	log.Listen(fn, func(f interface{}) {
		f.(func())()
	}, fmt.Sprintf("定时任务执行超时,桌子(%d)函数(%s)", log.GetFunctionName(fn)))
}

//用户掉线
func (this *Table) UserExitMsg(user *User) {
	if user == nil {
		return
	}
	log.UserInfoLog(user.GetId(), "收到用户断线消息 tableId:%d,roomId:%d", this.id, this.roomID)
	log.Listen(this.interGame.UserExit, func(f interface{}) {
		if f.(func(user inter.UserInetr) bool)(user) {
			//正常离开
			//this.funcLeaveGame(user)
			log.Listen(this.funcLeaveGame, func(f interface{}) {
				f.(func(user *User) bool)(user)
			}, fmt.Sprintf("离开 %d 函数名称:funcLeaveGame", user.GetId()))
		} else {
			//异常离开
			this.room.userManager.DeleteById(user.GetId())
			this.room.userManager.AddOffline(user)
			//设置用户状态为离开状态
			user.onlineStatus = g_UserLeave
			log.UserInfoLog(user.GetId(), "逻辑不允许用户断线 tableId:%d,roomId:%d", this.id, this.roomID)
		}

	}, fmt.Sprintf("离开 %d 函数名称:%s", user.GetId(), log.GetFunctionName(this.interGame.UserExit)))
}

//用户离开
func (this *Table) UserLeaveMsg(user *User) {
	log.UserInfoLog(user.GetId(), "收到用户离开消息 tableId:%d,roomId:%d", this.id, this.roomID)
	log.Listen(this.interGame.LeaveGame, func(f interface{}) {
		//log.Listen(this.interGame.UserExit, func(f interface{}) {
		if f.(func(user inter.UserInetr) bool)(user) {
			//正常离开
			log.Test("同意用户离开 %d", user.GetId())
			this.funcLeaveGame(user)
			log.Test("用户离开完成 %d", user.GetId())
		} else {
			//异常离开
			leave := &msg.S2CGeneralError{EType: 8, Descript: "游戏进行中，禁止退出！"}
			buffer, err := proto.Marshal(leave)
			if err == nil {
				user.sendMsgF(int32(msg.MSGKIND_ERROR), buffer)
				log.UserInfoLog(user.GetId(), "逻辑不允许用户离开 tableId:%d,roomId:%d", this.id, this.roomID)
			}
		}
	}, fmt.Sprintf("用户离开 %d", user.GetId()))
}

//发送场景
func (this *Table) SendSenceMsg(user *User) {
	log.UserInfoLog(user.GetId(), "发生用户发送场景消息 tableId:%d,roomId:%d", this.id, this.roomID)
	log.Listen(this.interGame.SendScene, func(f interface{}) {
		f.(func(user inter.UserInetr) bool)(user)
	}, fmt.Sprintf("发送场景 %d", user.GetId()))
	log.UserInfoLog(user.GetId(), "用户发送场景消息成功 tableId:%d,roomId:%d", this.id, this.roomID)
}

//用户准备消息
func (this *Table) UserReadyMsg(user *User) {
	log.UserInfoLog(user.GetId(), "收到用户准备消息 tableId:%d,roomId:%d", this.id, this.roomID)
	log.Listen(this.interGame.UserReady, func(f interface{}) {
		if f.(func(user inter.UserInetr) bool)(user) {
			//获取椅子id
			chairId := user.GetChairId()
			if chairId <= -1 {
				log.Warn("用户没有坐下")
				return
			}
			chair := this.chairs[chairId]
			chair.Ready()
			ready := &msg.S2CReady{UserId: user.GetId()}
			buffer, err := proto.Marshal(ready)
			if err == nil {
				user.sendMsgF(int32(msg.MSGKIND_READY), buffer)
				//this.room.funcSendMsg(int32(msg.CMDKIND_READY), user.GetId(), nil)
				log.Listen(user.funcSendMsg, func(f interface{}) {
					f.(func(int32, int64, []byte))(int32(msg.CMDKIND_READY), user.GetId(), nil)
				}, fmt.Sprintf("发生消息 %d", user.GetId()))
				if this.status == g_TableStart {
					user.GameRun(this.gameNum)
					c2sUserStart := &msg.C2SUserStart{GameId: user.gameId, MatchId: this.gameNum, RoomId: this.roomID, TableId: int32(this.id), PlatformId: this.platformId}
					c2sUserStart.Userids = append(c2sUserStart.Userids, user.GetId())
					data, _ := proto.Marshal(c2sUserStart)
					//this.room.funcSendMsg(int32(msg.CMDKIND_USERSTART), 0, data)
					log.Listen(user.funcSendMsg, func(f interface{}) {
						f.(func(int32, int64, []byte))(int32(msg.CMDKIND_USERSTART), 0, data)
					}, fmt.Sprintf("发送消息 %d", user.GetId()))
				}
				//this.interGame.GameStart(user)
				log.Listen(this.interGame.GameStart, func(f interface{}) {
					//log.Info("游戏开始调用%d %d", this.id, this.roomID)
					f.(func(inter.UserInetr) bool)(user)
				}, fmt.Sprintf("发送消息 %d", user.GetId()))
				log.UserInfoLog(user.GetId(), "用户准备成功 tableId:%d,roomId:%d", this.id, this.roomID)
			} else {
				log.Error(err.Error())
			}
		} else {
			log.Warn("用户准备失败")
			log.UserInfoLog(user.GetId(), "用户准备失败 tableId:%d,roomId:%d", this.id, this.roomID)
		}
	}, fmt.Sprintf("准备喜爱下 %d", user.GetId()))
}

//逻辑消息处理
func (this *Table) LogicMsg(msg *MsgTableChan) {
	log.Listen(this.interGame.OnGameMessage, func(f interface{}) {
		u := this.room.userManager.GetById(msg.User.GetId())
		if u != nil {
			f.(func(int32, []byte, inter.UserInetr))(msg.SubCmd, msg.Buffer, u)
		}
	}, fmt.Sprintf("逻辑消息 %d:%d", msg.User.GetId(), msg.SubCmd))
}

//获取血池
func (this *Table) GetRoomProb() (int32, error) {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return -1, errors.New("该桌子已经关闭")
	}
	t1 := time.Now().UnixNano()
	defer func() {
		t2 := time.Now().UnixNano()
		now := (t2 - t1) / 1000000
		if now > 10 {
			log.Warn("执行获取血池所用时间: %dms", now)
		}
	}()
	this.lock.RLock()
	defer this.lock.RUnlock()
	if this.roomID < 0 {
		return -1, errors.New("房间id为空")
	}
	log.Debug("获取血池platformId(%d) roomId(%d) tableId(%d）roomProb(%d)", this.platformId, this.roomID, this.id, this.roomProb)
	return this.roomProb, nil
}

func (this *Table) SetRoomProb(roomprob int32) {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return
	}
	this.lock.Lock()
	defer this.lock.Unlock()
	if this.roomID < 0 {
		return
	}
	this.roomProb = roomprob
	log.Debug("更新血池platformId(%d) roomId(%d) tableId(%d）roomProb(%d)", this.platformId, this.roomID, this.id, this.roomProb)
}

func (this *Table) GetRoomID() int64 {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return -1
	}
	return this.roomID
}

func (this *Table) GetEntranceRestrictions() int64 {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return -1
	}
	return this.entranceRestrictions
}

func (this *Table) GetPlatformID() int64 {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return -1
	}
	return this.platformId
}

func (this *Table) GetAdviceConfig() string {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return ""
	}
	return this.adviceConfig
}

//发送消息
func (this *Table) GameMessage(msg *MsgTableChan) {
	defer log.Trace()()
	if this.status == g_TableExit || this.waitInit {
		log.Warn("该桌子已经关闭")
		return
	}
	this.msgBuff <- msg
}

//全部重置
func (this *Table) Reset() {
	defer log.Trace()()
	//重置踢出所有用户
	log.Info("收到重制房间消息")
	this.reset <- true
	log.Info("重制房间消息通知成功")
	// for index := 0; index < len(this.chairs); index++ {
	// 	if this.chairs[index].user != nil {
	// 		log.Listen(this.interGame.LeaveGame, func(f interface{}) {
	// 			//log.Listen(this.interGame.UserExit, func(f interface{}) {
	// 			if f.(func(user inter.UserInetr) bool)(user) {
	// 				//正常离开
	// 				log.Test("同意用户离开 %d", user.GetId())
	// 				this.funcLeaveGame(user)
	// 				log.Test("用户离开完成 %d", user.GetId())
	// 			} else {
	// 				//异常离开
	// 				leave := &msg.S2CGeneralError{EType: 8, Descript: "游戏进行中，禁止退出！"}
	// 				buffer, err := proto.Marshal(leave)
	// 				if err == nil {
	// 					user.sendMsgF(int32(msg.MSGKIND_ERROR), buffer)
	// 					log.UserInfoLog(user.GetId(), "逻辑不允许用户离开 tableId:%d,roomId:%d", this.id, this.roomID)
	// 				}
	// 			}
	// 		}, fmt.Sprintf("用户离开 %d", user.GetId()))
	// 	}
	// }
	//log.Info("踢出用户")
}

//获取椅子
func (this *Table) GetChairById(id int) *Chair {
	defer log.Trace()()
	return this.chairs[id]
}

//获取机器人
func (this *Table) GetRobot(num int32) error {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return errors.New("该桌子已经关闭")
	}
	if this.platformId < 0 || this.roomID < 0 {
		return errors.New("没有初始化房间不能获取机器人")
	}
	if num <= 0 {
		return errors.New("0不能获取机器人")
	}
	log.Info("用户调用获取机器人%d:%d,num:%d(tableID:%d)", this.platformId, this.roomID, num, this.id)
	return this.room.funcGetRobot(this.platformId, this.roomID, int64(this.id), num)
}

//获取奖金池
func (this *Table) GetCollect(ration int32, userId int64) (int64, int64, error) {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return 0, -1, errors.New("该桌子已经关闭")
	}
	if this.platformId < 0 || this.roomID < 0 {
		return 0, 0, nil
	}
	ctx, cancel := context.WithTimeout(this.ctx, 1*time.Second)
	defer cancel()
	resp, err := this.room.funcGetCollect(ctx, this.roomID, ration, userId, this.gameNum)
	if err != nil {
		log.Error(err.Error())
		return 0, 0, err
	}
	return resp.Total, resp.Count, nil

}

//判断此桌子是否可用
func (this *Table) PlanChair(user *User, roomId int64, roomProb int32, level int32, roomRate, entranceRestrictions int64, adviceConfig string) (int, int, int) {
	defer log.Trace()()

	chairId := 0
	if this.platformId >= 0 {
		if user.platformId != this.platformId {
			log.Test("平台ID不正确%d", user.GetId())
			return define.SIT_DOWN_ERROR_NORMAL, 0, 0
		}
	}
	//判断入场条件是否到达
	if this.roomID > 0 {
		if this.roomID != roomId {
			log.Test("房间ID不正确%d:%d %d id:%d", this.roomID, int64(roomId), user.GetId(), this.id)
			return define.SIT_DOWN_ERROR_NORMAL, 0, 0
		}
	}
	if user.balance < entranceRestrictions {
		log.Test("入场金额不正确%d", user.GetId())
		return define.SIT_DOWN_ERROR_NORMAL, 0, 0
	}
	//判断是否开始
	if (this.count + 1) > this.max {
		log.Test("人数已经达到上线%d:%d id:%d", user.GetId(), this.count, this.id)
		return define.SIT_DOWN_ERROR_NORMAL, 0, 0
	}
	//表示可用直接分配
	for index := 0; index < len(this.chairs); index++ {
		//判断椅子是否可用
		if this.chairs[index].GetStatus() == 0 {
			chairId = this.chairs[index].GetNum()
			resp := this.interGame.OnActionUserSitDown(user, chairId, adviceConfig)
			if resp == define.SIT_DOWN_OK {
				//找到了 就坐下
				this.chairs[index].SetDown(user)
				chairId = this.chairs[index].GetNum()
				user.SetTableId(this.id)
				user.SetChairId(chairId)
				if roomProb != 0 {
					this.roomProb = roomProb
					log.Debug("匹配成功修改血池platformId(%d) roomId(%d) tableId(%d）roomProb(%d)", user.platformId, roomId, this.id, this.roomProb)
				}
				this.platformId = user.platformId
				this.entranceRestrictions = entranceRestrictions
				this.roomID = roomId
				this.adviceConfig = adviceConfig
				this.roomRate = roomRate
				this.level = level
				// if this.count <= 0 {
				// 	//开启机器人检测
				// 	this.RobotCheck()
				// }
				this.count++
				if user.IsRobot() == true {
					this.robotCount++
				}
				return resp, this.id, chairId
			} else {
				log.Test("逻辑不让用户坐下 %d", user.GetId())
				return resp, 0, 0
			}
		}
	}
	return define.SIT_DOWN_ERROR_NORMAL, -1, -1
}

//获取桌子id
func (this *Table) GetId() int {
	defer log.Trace()()
	return this.id
}

//设置空闲
func (this *Table) SetFree() {
	defer log.Trace()()
	this.status = g_TableFree
}

//设置开始
func (this *Table) SetStart() {
	defer log.Trace()()
	this.status = g_TableStart
}

//统一定时回调
func (this *Table) callback(inter interface{}) {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return
	}
	if this.roomID < 0 {
		//log.Warn("房间配置不正确，不执行定时%d", this.id)
		return
	}
	log.Test("执行定时任务,%d-%d-%d", this.id, this.roomID, this.platformId)
	this.timeCallBack <- inter.(func())
}

//添加定时器
func (this *Table) AddTimer(actionInterval time.Duration, jobFunc func()) (job *clock.Job, ok bool) {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return nil, false
	}
	if this.waitInit {
		log.Warn("该桌子已重置")
		return nil, false
	}
	log.Test("add time %s %v", log.GetFunctionName(jobFunc), jobFunc)
	//添加定时
	return this.clock.AddClock(actionInterval*time.Millisecond, 1, this.callback, jobFunc)
}

//添加重复定时器
func (this *Table) AddTimerRepeat(interval time.Duration, actionMax uint64, jobFunc func()) (jobScheduled *clock.Job, inserted bool) {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return nil, false
	}
	if this.waitInit {
		log.Warn("该桌子已重置")
		return nil, false
	}
	log.Test("添加定时任务%d", this.id)
	return this.clock.AddClock(interval*time.Millisecond, int(actionMax), this.callback, jobFunc)
}

//绑定游戏
func (this *Table) BindGame(interGame inter.GameInter) {
	defer log.Trace()()
	this.interGame = interGame
}

//发送场景消息
func (this *Table) SendScene(user *User) bool {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return false
	}
	this.SendSenceMsg(user)
	//this.sendScene <- user
	return true
}

//用户准备
func (this *Table) UserReady(user *User) bool {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return false
	}
	this.userReady <- user
	//log.Warn("准备执行准备消息%d", user.id)
	return true
}

//用户准备
func (this *Table) UserExit(user *User) bool {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return false
	}
	this.userExit <- user
	//log.Info("UserExit end")
	return true
}

//用户离开
func (this *Table) UserLeave(user *User) bool {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return false
	}
	this.userLeave <- user
	return true
}

//给大厅广播消息
func (this *Table) BroadcastAll(subCmd int32, pb proto.Message) error {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return errors.New("该桌子已经关闭")
	}
	if this.roomID < 0 {
		log.Warn("房间配置不正确，不执行定时%d", this.id)
		return errors.New("房间配置不正确，不执行定时")
	}
	log.Test("广播数据roomID:%d,id:%d", this.roomID, this.id)
	buff, err := proto.Marshal(pb)
	if err != nil {
		log.Warn(err.Error())
		return err
	}

	frameMsg := &msg.FrameMsg{MainCmd: int32(msg.MSGTYPE_SUBCMD), SubCmd: subCmd, Buff: buff, Time: time.Now().Unix()}
	data, err := proto.Marshal(frameMsg)
	if err != nil {
		log.Warn(err.Error())
		return err
	}
	return this.room.funcBroadcast(this.platformId, 0, data)
}

//开始游戏
func (this *Table) StartGame() {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return
	}
	if this.status != g_TableFree {
		log.Test("该局没有结束")
		return
	}
	this.status = g_TableStart
	num := this.GetRoomNum()
	this.gameNum = num
	log.Test("局开始 %d %d %s", this.id, this.roomID, this.gameNum)
	//发送开始
	//this.room.funcSendMsg(int32(msg.CMDKIND_START), 0, []byte(this.gameNum))

	for index := 0; index < len(this.chairs); index++ {
		user := this.chairs[index].GetUser()
		if user != nil {
			c2sUserStart := &msg.C2SUserStart{MatchId: this.gameNum, RoomId: this.roomID, TableId: int32(this.id), PlatformId: this.platformId}
			c2sUserStart.GameId = user.gameId
			c2sUserStart.Userids = append(c2sUserStart.Userids, user.GetId())
			data, err := proto.Marshal(c2sUserStart)
			if err != nil {
				log.Error(err.Error())
			} else {
				user.funcSendMsg(int32(msg.CMDKIND_USERSTART), 0, data)
				if !user.IsRobot() {
					log.Test("发送用户结束 %d", user.GetId())
				}
			}
		}
	}
	this.WriteLogs(0, "开始时间:"+time.Now().Format("2006-01-02 15:04:05"))
}

func (this *Table) GetRoomNum() string {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return ""
	}
	id := time.Now().Nanosecond()
	return fmt.Sprintf("%d%d%d%s", id, this.platformId, global.G_Config.GameId, rand.Rand4())
}

//结束游戏
func (this *Table) EndGame() {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return
	}
	if this.status != g_TableStart {
		log.Test("该局没有开始")
		return
	}
	this.WriteLogs(0, "结束时间:"+time.Now().Format("2006-01-02 15:04:05"))

	for index := 0; index < len(this.chairs); index++ {
		this.chairs[index].GameEnd(this.gameNum)
		//表示结算
		user := this.chairs[index].GetUser()
		if user != nil {

			if user.onlineStatus == g_UserLeave {
				log.Listen(this.interGame.UserExit, func(f interface{}) {
					if f.(func(inter.UserInetr) bool)(user) {
						//正常离开
						this.funcLeaveGame(user)
					} else {
						c2sUserStart := &msg.C2SUserStart{MatchId: this.gameNum, RoomId: this.roomID, TableId: int32(this.id), PlatformId: this.platformId}
						c2sUserStart.GameId = user.gameId
						c2sUserStart.Userids = append(c2sUserStart.Userids, user.GetId())
						data, err := proto.Marshal(c2sUserStart)
						if err == nil {
							user.funcSendMsg(int32(msg.CMDKIND_USEREND), 0, data)
							if !user.IsRobot() {
								log.Test("发送用户结束 %d", user.GetId())
							}
						} else {
							log.Error(err.Error())
						}

					}
				}, fmt.Sprintf("离开 %d", user.GetId()))
			} else {
				c2sUserStart := &msg.C2SUserStart{MatchId: this.gameNum, RoomId: this.roomID, TableId: int32(this.id), PlatformId: this.platformId}
				c2sUserStart.GameId = user.gameId
				c2sUserStart.Userids = append(c2sUserStart.Userids, user.GetId())
				data, err := proto.Marshal(c2sUserStart)
				if err == nil {
					user.funcSendMsg(int32(msg.CMDKIND_USEREND), 0, data)
					if !user.IsRobot() {
						log.Test("发送用户结束 %d", user.GetId())
					}
				} else {
					log.Error(err.Error())
				}

			}
			if this.isReset == true {
				log.Test("重置房间踢掉用户")
				log.Listen(this.interGame.LeaveGame, func(f interface{}) {
					//log.Listen(this.interGame.UserExit, func(f interface{}) {
					if f.(func(user inter.UserInetr) bool)(user) {
						//正常离开
						log.Test("同意用户离开 %d", user.GetId())
						this.funcLeaveGame(user)
						log.Test("用户离开完成 %d", user.GetId())
					}
				}, fmt.Sprintf("用户离开 %d", user.GetId()))
			}
		}
	}

	this.status = g_TableFree
	if len(this.records) > 2 {
		//上传日志
		c2sGameLog := &msg.C2SGameLog{
			MatchId:    this.gameNum,
			GameId:     global.G_Config.GameId,
			GameLogs:   this.records,
			PlatformId: this.platformId,
		}
		buff1, err := proto.Marshal(c2sGameLog)
		if err != nil {
			log.Error(err.Error())
		}
		this.room.funcWrietLogs(int32(msg.CMDKIND_GAMELOG), 0, buff1)
		log.Test("发生日志成功%v", c2sGameLog)
	}
	//清空上一轮切片
	this.records = make([]*msg.GameLog, 0)

	//查看是否需要关闭机器人
	_, ok := this.room.robotCtl.Load(fmt.Sprintf("%d-%d", this.platformId, this.roomID))
	if ok {
		for index := 0; index < len(this.chairs); index++ {
			if this.chairs[index].user != nil {
				if this.chairs[index].user.isRobot {
					this.room.funcSysOut(this.chairs[index].user.GetId())
				}
			}
		}
	}
	//判断是否重置桌子
	this.ResetTable()
}

func (this *Table) funcRobotControl(robotCtl msg.S2CRobotConfig_Action) {
	defer log.Trace()()
	if robotCtl == msg.S2CRobotConfig_ON {
		log.Warn("开启机器人%d-%d", this.platformId, this.roomID)
		this.room.robotCtl.Delete(fmt.Sprintf("%d-%d", this.platformId, this.roomID))
	}
	if robotCtl == msg.S2CRobotConfig_OFF {
		log.Warn("关闭机器人%d-%d", this.platformId, this.roomID)
		this.room.robotCtl.Store(fmt.Sprintf("%d-%d", this.platformId, this.roomID), robotCtl)
	}
}

//用户离开
func (this *Table) funcLeaveGame(user *User) bool {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return false
	}
	//获取椅子id
	chairId := user.GetChairId()
	if chairId <= -1 {
		log.Warn("用户没有坐下 id=%d,chairId=%d", user.GetId(), chairId)
		return false
	}
	chair := this.chairs[chairId]
	chair.Leave()
	if this.count > 0 {
		this.count--
	} else {
		log.Error("没有的用户")
		return false
	}
	if user.IsRobot() == true {
		if this.robotCount > 0 {
			this.robotCount--
		}
	}
	//发送用户的大码量
	if this.status == g_TableStart {

		user.GameEnd(this.gameNum)

		c2sUserStart := &msg.C2SUserStart{GameId: user.gameId, MatchId: this.gameNum, RoomId: this.roomID, TableId: int32(this.id), PlatformId: this.platformId}
		c2sUserStart.Userids = append(c2sUserStart.Userids, user.GetId())
		data, _ := proto.Marshal(c2sUserStart)
		user.funcSendMsg(int32(msg.CMDKIND_USEREND), 0, data)
		if !user.IsRobot() {
			log.Test("发送用户结束 %d", user.GetId())
		}
	}
	//广播所有用户离开并且删除用户
	leave := &msg.S2CLeave{UserId: user.GetId()}
	buffer, err := proto.Marshal(leave)
	if err == nil {
		user.sendMsgF(int32(msg.MSGKIND_LEAVE), buffer)
		//广播用户离开消息
		this.broadcastF(int32(msg.MSGKIND_LEAVE), buffer)
		if user.IsRobot() {
			this.room.funcReturnRobot(user.GetId())
		}
	} else {
		log.Error(err.Error())
	}

	user.funcSendMsg(int32(msg.CMDKIND_LEAVE), user.GetId(), nil)

	user.EXit()
	this.room.userManager.DeleteById(user.GetId())
	this.room.userManager.DeleteOfflineById(user.GetId())
	if !user.IsRobot() {
		log.UserInfoLog(user.GetId(), "用户离开 tableId:%d,roomId:%d", this.id, this.roomID)
	}
	return true
}

func (this *Table) ResetTable() {
	//非百人场清空配置
	if this.count <= 0 {
		if global.G_Config.GameType == 2 || global.G_Config.GameType == 4 || global.G_Config.GameType == 5 || global.G_Config.GameType == 6 || this.isReset == true {
			this.clock.Reset()
			this.timeCallBack = make(chan func(), this.max)
			if global.G_Config.GameType == 1 || global.G_Config.GameType == 3 {
				this.room.openRoom.Delete(fmt.Sprintf("%d-%d", this.platformId, this.roomID))
			}
			this.count = 0
			this.adviceConfig = ""
			this.platformId = -1
			this.entranceRestrictions = -1
			this.roomID = -1
			this.level = 0
			this.roomProb = 0
			this.roomRate = 0
			this.status = g_TableFree
			//清空切片
			for index := 0; index < len(this.chairs); index++ {
				this.chairs[index].Leave()
			}
			log.Listen(this.interGame.ResetTable, func(f interface{}) {
				f.(func())()
			}, fmt.Sprintf("调用逻辑重置桌子"))

			//this.RobotCheck()
			this.isReset = false
			log.Test("结束重置房间:%d", this.id)
			//开启定时器检测
			this.RobotCheck()
			//结束时间
			this.endTable = time.Now().UnixNano()
		}
	}
}

/*
*踢人
 */
func (this *Table) KickOut(user inter.UserInetr) {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return
	}
	log.Test("踢出用户%d", user.GetId())
	this.funcLeaveGame(user.(*User))
	return
}

//桌子群发消息
func (this *Table) Broadcast(subCmd int32, pb proto.Message) {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return
	}
	for index := 0; index < len(this.chairs); index++ {
		if this.chairs[index].user != nil {
			this.chairs[index].user.SendMsg(subCmd, pb)
		}
	}

}

//桌子群发消息
func (this *Table) broadcastF(subCmd int32, buff []byte) {
	defer log.Trace()()
	if this.status == g_TableExit {
		log.Warn("该桌子已经关闭")
		return
	}
	for index := 0; index < len(this.chairs); index++ {
		if this.chairs[index].user != nil {
			this.chairs[index].user.sendMsgF(subCmd, buff)
		}
	}
}

//创建跑马灯
func (this *Table) CreateMarquee(nickName string, gold int64, special string, ruleId int64) error {
	defer log.Trace()()
	//log.Info("%d:%d创建跑马灯", this.roomID, this.platformId)
	if this.roomID < 0 || this.platformId < 0 {
		return errors.New("房间还没启动")
	}
	lg := utf8.RuneCountInString(nickName)
	chenge := "****"
	if lg == 1 {
		nickName += chenge
	}
	if lg == 2 {
		nickName = string([]rune(nickName)[:1]) + chenge + string([]rune(nickName)[2:])
	}
	if lg == 3 {
		nickName = string([]rune(nickName)[:2]) + chenge + string([]rune(nickName)[2:])
	}
	if lg >= 4 {
		nickName = string([]rune(nickName)[:2]) + chenge + string([]rune(nickName)[lg-2:])
	}

	value, ok := this.room.marqueeConfig.Load(fmt.Sprintf("%d", ruleId))
	if ok {
		config := value.(*msg.MarqueeConfig)
		if config.RoomId != fmt.Sprintf("%d", this.roomID) || config.PlatformId != this.platformId {
			log.Warn("%d:%d获取跑马灯配置%v", this.roomID, this.platformId, config)
			return errors.New("获取跑马灯的房间id或者平台不一致")
		}
		str := config.Content
		new := ""
		pos := 0
		for i := 0; i < len(str); i++ {
			if str[i] == '%' {
				if str[i+1] == 'n' {
					new += str[pos:i]
					pos = i + 2
					i++
					new += nickName
				}
				if str[i+1] == 'g' {
					new += str[pos:i]
					pos = i + 2
					i++
					new += global.G_Config.ServerName
				}
				if str[i+1] == 'l' {
					new += str[pos:i]
					pos = i + 2
					i++
					if this.level == 1 {
						new += "初级房"
					}
					if this.level == 2 {
						new += "中级房"
					}
					if this.level == 3 {
						new += "高级房"
					}
					if this.level == 4 {
						new += "大师房"
					}

				}
				if str[i+1] == 'm' {
					new += str[pos:i]
					pos = i + 2
					i++
					new += fmt.Sprintf("%.2f", float64(gold)/100.00)
				}
				if str[i+1] == 's' {
					new += str[pos:i]
					pos = i + 2
					i++
					new += special
				}
			}
		}
		new += str[pos:]
		c2sMarquee := &msg.C2SMarquee{GameId: global.G_Config.GameId, PlatformId: this.platformId, Content: new, RuleId: ruleId}
		broadcastsData, err := proto.Marshal(c2sMarquee)
		if err != nil {
			log.Warn(err.Error())
			return err
		}
		for index := 0; index < len(this.chairs); index++ {
			if this.chairs[index].user != nil {
				this.chairs[index].user.funcSendMsg(int32(msg.CMDKIND_MARQUEE), 0, broadcastsData)
				//log.Info("发送跑马灯 %v", c2sMarquee)
				break
			}
		}
		return nil
	} else {
		return errors.New(fmt.Sprintf("跑马灯配置不存在%d", ruleId))
	}
}

//获取跑马灯配置
func (this *Table) GetMarqueeConfig() (configs []*msg.MarqueeConfig) {
	log.Test("%d:%d获取跑马灯配置", this.roomID, this.platformId)
	if this.roomID < 0 || this.platformId < 0 {
		return
	}
	//遍历跑马灯配置
	this.room.marqueeConfig.Range(func(k, v interface{}) bool {
		config := v.(*msg.MarqueeConfig)
		if config.RoomId == fmt.Sprintf("%d", this.roomID) && config.PlatformId == this.platformId {
			log.Test("%d:%d获取跑马灯配置%v", this.roomID, this.platformId, config)
			configs = append(configs, config)
		}
		return true
	})
	return
}
